<?php


namespace App\Services;

use App\Models\Footage;
use App\Models\Product;
use App\Models\Video;
use App\Utils\Code;
use App\Utils\VideoUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class ProductService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            if (Product::where('name', $params['name'])->exists()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model = new Product();
            $model->type = $params['type'];
            $model->name = $params['name'];
            $model->path = $params['path'];
            if (isset($params['footage_id']) && $params['footage_id']) {
                $footage = Footage::find($params['footage_id']);
                if (!$footage) {
                    throw new \Exception('不存在的镜头组ID', Code::EMPTY_DATA);
                }
                $model->footage_id = $footage->id;
                $model->papper_id = $footage->papper_id;
                $model->save();
                $footage->status = 2;
                $footage->save();
                foreach($footage->parts as $part) {
                    if ($part->video_id) {
                        $video = Video::find($part->video_id);
                        if ($video) {
                            $video->use_count += 1;
                            $video->save();
                        }
                    }
                }
            } else {
                $model->footage_id = 0;
                $model->papper_id = 0;
            }
            if (isset($params['papper_id']) && $params['papper_id']) {
                $model->papper_id = $params['papper_id'];
            }
            $model->save();
            return $model;
        });
    }

    public function checkExists(array $params) {
        if (!isset($params['name']) || !$params['name']){
            throw new \Exception('名称不能为空', Code::PARAMETER_ERROR);
        }
        if (Product::where('name', $params['name'])->exists()) {
            throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
        }
        return true;
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Product::where('id', $id)->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            if (Product::where('name', $params['name'])->where('id', '<>', $id)->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model = $this->show($id);
            if (isset($params['type']) && $params['type']) {
                $model->type = $params['type'];
            }
            if (isset($params['name']) && $params['name']) {
                $model->name = $params['name'];
            }
            if (isset($params['path']) && $params['path']) {
                $model->path = $params['path'];
            }
            if (isset($params['papper_id']) && $params['papper_id']) {
                $model->papper_id = $params['papper_id'];
            }
            $model->save();
            return $model;
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Product::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        if (isset($params['mode']) && $params['mode'] == 'select') {
            $model = Product::select(['id', 'name']);
        } else {
            $model = Product::with([
                'footage',
                'papper' => function ($query) {
                    $query->with([
                        'folder',
                        'title',
                        'account' => function ($query) {
                            $query->with([
                                'ip',
                                'platforms'
                            ])->select(['id', 'name', 'ip_id']);
                        }
                    ])->select(['id', 'content', 'account_id', 'folder_id', 'status']);
                }
            ]);
        }
        if (isset($params['footage_id']) && $params['footage_id']) {
            $model = $model->where('footage_id', '=', $params['footage_id']);
        }
        if (isset($params['name']) && $params['name']) {
            $model = $model->where('name', 'like', '%'.$params['name'].'%');
        }
        if (isset($params['papper_id']) && $params['papper_id']) {
            $model = $model->where('papper_id', '=', $params['papper_id']);
        } else if (!$this::$admin) {
            throw new \Exception('你没有权限查看全部成品视频', Code::LACK_OF_CONDITIONS);
        }
        if (isset($params['folder_id']) && $params['folder_id']) {
            $model = $model->whereHas('papper', function ($query) use ($params){
                $query->where('folder_id', '=', $params['folder_id']);
            });
        }
        $lists = $model->orderBy('id', 'desc')->paginate(isset($params['per_page']) ? (int)$params['per_page'] : 15);
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'type' => ['bail', 'required', 'integer'],
            'name' => ['bail', 'required', 'string'],
            'path' => ['bail', 'required', 'string'],
            'footage_id' => ['bail', 'nullable', 'integer']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'type' => '类型',
            'name' => '成品名称',
            'path' => '预览视频路径',
            'footage_id' => '镜头组ID'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
